/*============================================================================
 PROJECT: Kleii
 FILE:    MKAssetsPickerViewController.m
 AUTHOR:  Khoai Nguyen Minh
 DATE:    12/21/13
 =============================================================================*/

/*============================================================================
 IMPORT
 =============================================================================*/
#import "MKAssetsPickerViewController.h"
#import "AssetLibraryHelper.h"
#import "KKGridView.h"
#import "MKAssetView.h"

/*============================================================================
 PRIVATE MACRO
 =============================================================================*/
#define kAssetViewSize  100
#define kAssetViewTag   9999
#define kPhotoTypeIcon  @"icon_photo"
#define kVideoTypeIcon  @"icon_video"
#define kCheckIcon      @"icon_check_bottom"
#define kUnCheckIcon    @"icon_uncheck_bottom"

/*============================================================================
 PRIVATE INTERFACE
 =============================================================================*/

@interface MKAssetsPickerViewController ()<KKGridViewDataSource, KKGridViewDelegate>
@property (nonatomic, strong) KKGridView  *gridView;
@property (nonatomic, strong) NSMutableArray  *assests;
@property (nonatomic, strong) NSMutableIndexSet *selectedIndexes;
@end

@implementation MKAssetsPickerViewController

#pragma mark - Create Subviews

- (void)addGridView {
    /* get correct rect of grid view */
    CGRect rect = self.view.bounds;
    KKGridView *tempGridView = [[KKGridView alloc] initWithFrame:rect];
    tempGridView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    tempGridView.delegate = self;
    tempGridView.dataSource = self;
    self.gridView = tempGridView;
    [self.view addSubview:self.gridView];
}

#pragma mark - Initialization

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleLabel.text = NSLocalizedString(@"Assets", nil);
    self.selectedIndexes = [NSMutableIndexSet indexSet];
    
    /* add grid view */
    [self addGridView];
    
    /* collect assets */
    [[AssetLibraryHelper sharedPhotoLibraryAccessor] getAssetsFromGroup:self.group
                                                            resultBlock:^(NSMutableArray *assets, NSError *error) {
                                                                self.assests = assets;
                                                                [self.gridView reloadData];
                                                            }];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - KKGridViewDataSource

- (NSUInteger)numberOfSectionsInGridView:(KKGridView *)gridView {
    return 1;
}

- (NSUInteger)gridView:(KKGridView *)gridView numberOfItemsInSection:(NSUInteger)section {
    return [self.assests count];
}

- (KKGridViewCell *)gridView:(KKGridView *)gridView cellForItemAtIndexPath:(KKIndexPath *)indexPath {

    KKGridViewCell *cell = [KKGridViewCell cellForGridView:gridView customizeBlock:^(KKGridViewCell *aCell) {
        aCell.reuseIdentifier = @"MKAssetView";
        LayerBorderWithSizeColor(aCell.layer, 0.5, UIColorFromRGB(0x41aec8));
        aCell.layer.masksToBounds = YES;
        
        /* create customize view */
        MKAssetView *view = [[IBHelper sharedUIHelper] loadViewNib:aCell.reuseIdentifier];
        view.checkedMarkImageView.image = [[IBHelper sharedUIHelper] loadImage:kCheckIcon];
        view.tag = kAssetViewTag;
        view.callback = ^(MKAssetView *_assetView) {
            KKIndexPath *idx = [gridView indexPathForCell:(KKGridViewCell *)_assetView.superview.superview];
            if(idx) {
                if(_assetView.checkedMarkImageView.hidden) {
                    [self.selectedIndexes removeIndex:idx.index];
                } else {
                    [self.selectedIndexes addIndex:idx.index];
                }
            }
        };
        
        [aCell.contentView addSubview:view];
    }];
    
    /* get asset and update cell information */
    MKAssetView *assetView = (MKAssetView *)[cell.contentView viewWithTag:kAssetViewTag];
    assetView.overlayView.hidden = ![self.selectedIndexes containsIndex:indexPath.index];
    assetView.frame = cell.bounds;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // switch to a background thread and perform your expensive operation
        ALAsset *asset = [self.assests objectAtIndex:indexPath.index];
        UIImage *image = [asset thumbnailImage];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            /* update thumbnail image & check mark */
            assetView.coverImageView.image = image;
            assetView.typeImageView.image = [[IBHelper sharedUIHelper] loadImage:([asset isPhoto] ? kPhotoTypeIcon : kVideoTypeIcon)];
            assetView.checkedMarkImageView.hidden = ![self.selectedIndexes containsIndex:indexPath.index];
        });
    });
    
    return cell;
}

- (void)gridView:(KKGridView *)gridView didSelectItemAtIndexPath:(KKIndexPath *)indexPath {
    /* deselete cell at index path */
    [gridView deselectItemsAtIndexPaths:@[indexPath] animated:NO];
    
}

@end
